import { Controller } from 'egg';
import puppeteer from 'puppeteer';
import path from 'path';
import {autoScroll} from '../utils';

export default class HomeController extends Controller {
  public async index() {
    const { ctx } = this;
    // 启动浏览器
    const browser = await puppeteer.launch({
      headless: true, // 是否无头
      args: [ '--no-sandbox', '--font-render-hinting=medium' ],
    });
    const page = await browser.newPage();
    const url = 'http://localhost:3000/demospa/demoView?comData=%5B%7B%22kk%22%3A%22%E5%8F%82%E6%95%B0%22%2C%22type%22%3A%22Text1%22%2C%22title%22%3A%22Text1%E7%BB%84%E4%BB%B6%22%2C%22props%22%3A%7B%22t%22%3A%22%E6%A0%87%E9%A2%98%E5%86%85%E5%AE%B9%22%7D%7D%2C%7B%22kk%22%3A%22%E5%8F%82%E6%95%B0%22%2C%22type%22%3A%22Header%22%2C%22title%22%3A%22header%E7%BB%84%E4%BB%B6%22%2C%22props%22%3A%7B%22name%22%3A12323%2C%22context%22%3A%22%E5%AF%B9%E4%BA%8E%E4%B8%8D%E5%B8%B8%E7%94%A8%E7%9A%84%E8%AF%8D%E6%88%96%E8%80%85%E6%96%B0%E5%88%9B%E9%80%A0%E7%9A%84%E8%AF%8D%EF%BC%8C%E9%9C%80%E8%A6%81%E5%AE%9A%E4%B9%89%E5%92%8C%E6%8F%8F%E8%BF%B0%EF%BC%8C%E5%8F%AF%E4%BB%A5%E6%A0%B9%E6%8D%AE%E9%9C%80%E6%B1%82%E8%87%AA%E8%A1%8C%E5%88%A0%E5%87%8F%E6%AD%A4%E6%A8%A1%E5%9D%97%E3%80%82%22%7D%2C%22editor%22%3A%7B%22name%22%3A%7B%22type%22%3A%22input%22%2C%22label%22%3A%22%E6%A0%87%E9%A2%98%22%7D%2C%22context%22%3A%7B%22type%22%3A%22input%22%2C%22label%22%3A%22%E6%A0%87%E9%A2%98%22%7D%7D%7D%2C%7B%22kk%22%3A%22%E5%8F%82%E6%95%B0%22%2C%22type%22%3A%22Table1%22%2C%22title%22%3A%22Table1%E7%BB%84%E4%BB%B6%22%2C%22props%22%3A%7B%7D%7D%5D';
    await page.goto(url, {
      // timeout: 60000,
      waitUntil: 'networkidle2', // networkidle2 会一直等待，直到页面加载后不存在 2 个以上的资源请求，这种状态持续至少 500 ms
    });


    const ext = '.pdf';
    const key = 'node_demo' + ext;
    const _path = path.resolve(`${__dirname}/../../`, key);
    console.log('>>>', __dirname, _path);
    await autoScroll(page);
    await page.pdf({ path: _path, format: 'a4' });
    // await browser.close();
    ctx.body = '生成pdf成功';
  }
}
